import React, { useMemo, memo } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  StyleSheet,
  Platform,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import { Avatar, CheckBox } from "@rneui/themed";
import { Friend } from "@/types/friend";
import { styles } from "./index.style";
import {
  GroupMember,
  GroupMembersListMode,
  GroupMemberRole,
  GroupMembersListProps,
} from "@/types/group-chat";

const GroupMembersList: React.FC<GroupMembersListProps> = memo(
  ({
    mode,
    friends,
    loading,
    selectedIds,
    onSelectItem,
    groupMembers = [],
    isAdmin = false,
    isOwner = false,
  }) => {
    const { colors } = useTheme();

    // 根据模式确定可操作的项目
    const canInteractWithItem = (itemId: string) => {
      if (mode === GroupMembersListMode.INVITE) {
        // 邀请模式：非群成员可操作
        return !groupMembers.includes(itemId);
      } else if (mode === GroupMembersListMode.REMOVE) {
        // 移除模式：是群成员且有权限(管理员或群主)可操作
        return groupMembers.includes(itemId) && (isAdmin || isOwner);
      }
      return false;
    };

    const filteredFriends = useMemo(() => {
      if (!Array.isArray(friends)) return [];

      if (mode === GroupMembersListMode.REMOVE) {
        // 移除模式：只显示群成员
        return friends.filter(
          (friend) => friend?.id && groupMembers.includes(friend.id)
        );
      }
      return friends;
    }, [friends, groupMembers, mode]);

    // 获取显示名称，优先级：群聊备注 > 好友备注 > 昵称
    const getDisplayName = (item: Friend | GroupMember) => {
      // 检查是否有群聊备注
      if ("groupRemark" in item && item.groupRemark) {
        return item.groupRemark;
      }
      // 其次是好友备注
      if (item.remark) {
        return item.remark;
      }
      // 最后是昵称
      return item.nickname || "未命名用户";
    };

    // 获取角色标签文本
    const getRoleTag = (item: Friend | GroupMember) => {
      if ("role" in item) {
        if (item.role === GroupMemberRole.OWNER) return "群主";
        if (item.role === GroupMemberRole.ADMIN) return "管理员";
        return "成员";
      }
      return null; // 没有角色信息
    };

    // 渲染好友/成员项 - 使用useMemo缓存渲染函数
    const renderItem = useMemo(() => {
      return ({ item }: { item: Friend | GroupMember }) => {
        if (!item || !item.id) return null;

        const isSelected = selectedIds.includes(item.id);
        const isGroupMember = groupMembers.includes(item.id);
        const displayName = getDisplayName(item);
        const canInteract = canInteractWithItem(item.id);
        const roleTag = getRoleTag(item);

        return (
          <TouchableOpacity
            style={[
              styles.itemContainer,
              {
                borderBottomColor: colors.border.divider,
              },
            ]}
            onPress={() => canInteract && onSelectItem(item.id)}
            disabled={!canInteract}
          >
            <Avatar
              rounded
              size={40}
              source={{
                uri:
                  item.avatar ||
                  "https://randomuser.me/api/portraits/men/32.jpg",
              }}
              containerStyle={styles.avatar}
            />

            <View style={styles.infoContainer}>
              <View style={styles.nameContainer}>
                <Text style={[styles.nameText, { color: colors.text.primary }]}>
                  {displayName}
                </Text>
                {roleTag && (
                  <View
                    style={[
                      styles.roleTag,
                      {
                        backgroundColor:
                          roleTag === "群主"
                            ? "rgba(255, 59, 48, 0.1)"
                            : roleTag === "管理员"
                            ? "rgba(0, 122, 255, 0.1)"
                            : "rgba(142, 142, 147, 0.1)",
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.roleText,
                        {
                          color:
                            roleTag === "群主"
                              ? colors.status.error
                              : roleTag === "管理员"
                              ? colors.primary
                              : colors.text.secondary,
                        },
                      ]}
                    >
                      {roleTag}
                    </Text>
                  </View>
                )}
              </View>

              {/* 如果有群聊备注但显示的是好友备注或昵称，则显示原始昵称 */}
              {"groupRemark" in item &&
                item.groupRemark &&
                displayName !== item.nickname && (
                  <Text
                    style={[
                      styles.originalName,
                      { color: colors.text.secondary },
                    ]}
                  >
                    昵称: {item.nickname}
                  </Text>
                )}

              {/* 如果没有群聊备注但显示的是好友备注，则显示原始昵称 */}
              {(!("groupRemark" in item) || !item.groupRemark) &&
                item.remark &&
                displayName === item.remark && (
                  <Text
                    style={[
                      styles.originalName,
                      { color: colors.text.secondary },
                    ]}
                  >
                    昵称: {item.nickname}
                  </Text>
                )}

              {mode === GroupMembersListMode.INVITE && isGroupMember && (
                <Text
                  style={[styles.statusTag, { color: colors.text.secondary }]}
                >
                  已是群成员
                </Text>
              )}
            </View>

            {canInteract &&
              (mode === GroupMembersListMode.INVITE ? (
                <CheckBox
                  checked={isSelected}
                  onPress={() => onSelectItem(item.id)}
                  checkedColor={colors.primary}
                  uncheckedColor={colors.border.light}
                  containerStyle={styles.checkbox}
                />
              ) : (
                <TouchableOpacity
                  style={[
                    styles.removeButton,
                    isSelected && { backgroundColor: "rgba(255, 59, 48, 0.3)" },
                  ]}
                  onPress={() => onSelectItem(item.id)}
                >
                  <Text
                    style={[
                      styles.removeText,
                      { color: colors.text.primary },
                      isSelected && { fontWeight: "700" },
                    ]}
                  >
                    {isSelected ? "已选择" : "移除"}
                  </Text>
                </TouchableOpacity>
              ))}
          </TouchableOpacity>
        );
      };
    }, [colors, groupMembers, mode, onSelectItem, selectedIds]);

    // 列表为空时的组件
    const EmptyComponent = () => (
      <View style={styles.centerContainer}>
        <Ionicons
          name="people-outline"
          size={48}
          color={colors.text.secondary}
        />
        <Text style={[styles.messageText, { color: colors.text.secondary }]}>
          {mode === GroupMembersListMode.INVITE
            ? "暂无好友可邀请"
            : "暂无群成员可管理"}
        </Text>
      </View>
    );

    // 加载中组件
    const LoadingComponent = () => (
      <View style={styles.centerContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
        <Text style={[styles.messageText, { color: colors.text.secondary }]}>
          加载中...
        </Text>
      </View>
    );

    // 如果正在加载，显示加载组件
    if (loading) {
      return <LoadingComponent />;
    }

    return (
      <FlatList
        data={filteredFriends}
        renderItem={renderItem}
        keyExtractor={(item) => item?.id || Math.random().toString()}
        style={[styles.listContainer, { backgroundColor: colors.background }]}
        showsVerticalScrollIndicator={true}
        contentContainerStyle={[
          { paddingBottom: 20 },
          (!filteredFriends || filteredFriends.length === 0) && {
            flex: 1,
            justifyContent: "center",
          },
        ]}
        maxToRenderPerBatch={10}
        initialNumToRender={10}
        windowSize={5}
        removeClippedSubviews={Platform.OS !== "web"}
        ListEmptyComponent={EmptyComponent}
      />
    );
  }
);

export default GroupMembersList;
